package com.sjt.demo12;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
/*
  连接池
 */
@Data
@Slf4j
public class ConnectionPool   {

    // 空闲线程集合
    private final List<Connection> freeConnection = new ArrayList<>();

    // 活动线程集合
    private final List<Connection> activeConnection = new ArrayList<>();

    private final String url = "jdbc:mysql://localhost:3306/blog";

    private final String userName = "root";

    private final String password = "root";

    //最大连接数
    private final int maxConnections = 10;

    // 最大允许的连接数
    private final int maxActiveConnections = 10;

    ;// 连接超时时间
    private final long connectionTimeOut = 1000 * 60 * 20;

    // 记录线程总数
    private static int connCount = 0;


    //根据传进来的初始连接数创建连接
    public ConnectionPool(int initConnections) {

        for (int i = 0; i <initConnections; i++) {
            Connection newConnection = createConnection();
            if (newConnection != null) {
                freeConnection.add(newConnection);
            }
        }
    }

    // 创建新的Connection
    private Connection createConnection() {
        try {

            Connection connection = DriverManager.getConnection(url,userName, password);
            connCount++;
            return connection;
        } catch (Exception e) {
            return null;
        }

    }


    //尝试获取连接
    public Connection getConnection() {

        Connection connection = null;
        try {
            //判断是否还有连接可以用
            if (connCount < maxActiveConnections) {

                if (freeConnection.size() > 0) {
                    connection = freeConnection.remove(0);
                } else {

                    connection = createConnection();
                }
                    activeConnection.add(connection);

            } else {
                log.debug("没有连接了，需要等待");

                // 进行等待,重新获取连接
                Thread.currentThread().wait(connectionTimeOut);

                //不断尝试获取连接
                connection = getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }


    //释放连接
    public void releaseConnection(Connection connection) {
        try {
            if (connection == null) {
                return;
            }
                // 判断空闲线程数是否大于最大线程数
                if (freeConnection.size() < maxConnections) {
                    freeConnection.add(connection);
                } else {
                    connection.close();
                }
                activeConnection.remove(connection);
                connCount--;
                notifyAll();

        } catch (Exception ignored) {

        }

    }

}

